<?
#     Xepec.ru - социальная сеть
#     Copyright (C) 2008  Fedorchenko Alexander
#
#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.
#
#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#     Autor: Fedorchenko Alexander
#     Mail: sos20@list.ru
#     Date: 17/01/2009
#
#
#
#     У библиотеке статус НЕСТАБИЛЬНАЯ
#     Нестабильно работает определение кодировки
#     Не стабильно работает mp3_tags_write()


include("../config.php");

function convert_tag_encoding($str)
{
	#TODO: Отладить определение кодировки
	#FIXME: Она плохо работает и помоему только приодной из версий тегов

 //	if (!(preg_match('//u', $str)))
 //	{
#
# 		for ( $i = 0, $length = strlen($str); $i < $length; $i++ )
# 		{
# 			$char = ord($str[$i]);
# 			//non-russian characters
# 			if ($char < 128 || $char > 256)
# 			{
# 				//есть кириллица
				$tag=mb_convert_encoding($str, 'Windows-1252','UTF-8');
				$tag=mb_convert_encoding($tag, 'UTF-8','Windows-1251');
				return $tag;
# 			}
# 		}
#
#
#
 //	}
 //	else return $str;
#
 }
function music_file_type()
{
	
}

function music_file_add()
{
	
}

function mp3_tags_read($mp3_file_name)
{
	$read = new Reader($mp3_file_name);
	$head = new ID3_Header($read);
	$header_version = $head->getVersion();
#	echo '<br><b>'.$header_version."<br></b>";


	#TODO: Переделать способ определения версии тегов
	# как вариант, через команду file в linux`е
	# или как вариант смотри в файле: c/id3.c

	if ($header_version < 0)
	{
		#В фаиле только теги 3v2
		require_once("ID3v1.php");


		$id3v1 = new ID3v1($mp3_file_name);
		#$title = $id3->getTitle();
		#$year = $id3->getTitle();

		$mp3_tag_3v1 = array # Массив с тэгама mp3`шника
		(
			"title"		=>	$id3v1->getTitle(),
			"artist"	=>	$id3v1->getArtist(),
			"album"		=>	$id3v1->getAlbum(),
			"year"		=>	$id3v1->getYear(),
			"genre"		=>	$id3v1->getGenre(),
			"track"		=>	$id3v1->getTrack()
		);
		#echo 'Название песни:  <b>'.$mp3_tag_3v1['title']."</b><br>";
		#if($debug == TRUE)
		#print_r($mp3_tag_3v1);
		return $mp3_tag_3v1;
	}

	else
	{
		require_once("ID3v2.php");

		$id3v2 = new ID3v2($mp3_file_name);

		$mp3_tag_3v2 = array
		(
			"title"		=>	convert_tag_encoding($id3v2->tit2->text),
			"artist"	=>	convert_tag_encoding($id3v2->tpe1->text),
			"album"		=>	convert_tag_encoding($id3v2->talb->text),
			"year"		=>	convert_tag_encoding($id3v2->tyer->text),
			#"genre"		=>	$id3v2->getFramesByIdentifier("TYER"),######
			"track"		=>	convert_tag_encoding($id3v2->trck->text)
		);
#		print_r($mp3_tag_3v2);


		#Проверка изменились ли тэги
		$tag=convert_tag_encoding($id3v2->tit2->text);
		if ($tag == $id3v2->tit2->text)
		{
#			if($debug!=TRUE)echo "<br>Тэги не были изменены<br>";
		}
		else
		{
#			if($debug!=TRUE)echo "<br><b>Теги были конвертированы</b><br>";

		}



		#$frame = $id3v2->getFramesByIdentifier("TIT2"); // for song title; or TALB for album title; ..
		#$title = $frame[0]->getText();
#echo 'Название песни:  <b>'.$tag."</b>";

		#$frs = $id3v2->getFrames();
		#echo "<br><br><br>";
		#print_r($frs);


		$title = $id3v2->tit2->text;	#contains the first song title; or talb->text for album title;
		$image = $id3v2->apic->imageType;
#echo "<br>Идефикатор картинки: <b>".$image."</b>";
			#$frame = $id3->getFramesByIdentifier("APIC"); // for attached picture
			#$image = $frame[0]->getImageType();

		#$frame = $id3->getFramesByIdentifier("APIC"); // for attached picture
		return $mp3_tag_3v2;
	}
}

function mp3_tags_write($mp3_file_name, $tag, $str)
{
	#FIXME: Нужно протестировать функцию были неполадки
	# Способ не очень хороший
	# И попять-же определение версии тегов(см.mp3_tags_read())

	require_once("ID3v1.php");
	require_once("ID3v2.php");

	$read = new Reader($mp3_file_name);
	$head = new ID3_Header($read);
	$header_version = $head->getVersion();

	if($debug==TRUE) $error=$error."Найденая версия тега:".$header_version."\n";

	switch ($tag)
	{
		case 'title':
			if ($header_version < 0)
			{
				$id3v1 = new ID3v1();
				$id3v1->setTitle($str);
				$id3v1->write($mp3_file_name);
			}
			else
			{
				$id3v2 = new ID3v2($mp3_file_name);
				$id3v2->tit2->text=$str;
				$id3v2->write();

			}
		break;
		case 'artist':
			if ($header_version < 0)
			{
				$id3v1 = new ID3v1();
				$id3v1->setArtist($str);
				$id3v1->write($mp3_file_name);
			}
			else
			{
				$id3v2 = new ID3v2($mp3_file_name);
				$id3v2->tpe1->text = $str;
				$id3v2->write();

			}
		break;
		case 'album':
			if ($header_version < 0)
			{
				$id3v1 = new ID3v1();
				$id3v1->setAlbum($str);
				$id3v1->write($mp3_file_name);
			}
			else
			{
				$id3v2 = new ID3v2($mp3_file_name);
				$id3v2->talb->text = $str;
				$id3v2->write();

			}
		break;
		case 'year':
			if ($header_version < 0)
			{
				$id3v1 = new ID3v1();
				$id3v1->setYear($str);
				$id3v1->write($mp3_file_name);
			}
			else
			{
				$id3v2 = new ID3v2($mp3_file_name);
				$id3v2->tyer->text = $str;
				$id3v2->write();

			}
		break;
		case 'genre':
			if ($header_version < 0)
			{
				$id3v1 = new ID3v1();
				$id3v1->setGenre($str);
				$id3v1->write($mp3_file_name);
			}
			else
			{
				#FIXME: Нужна функция преобразования жанра межеду v1 & v2
				#Сложность в том, что в v1 жанр стриноговая переменная:
				#
				#id3_genres[148] = { "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age",
				#	"Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska", "Death Metal", "Pranks",
				#	"Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", "Trance", "Classical", "Instrumental", "Acid",
				#	"House", "Game", "Sound Clip", "Gospel", "Noise", "Alternative Rock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop",
				#	"Instrumental Rock", "Ethnic", "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock",
				#	"Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native US", "Cabaret", "New Wave", "Psychedelic", "Rave",
				#	"Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk",
				#	"Folk-Rock", "National Folk", "Swing", "Fast Fusion", "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock",
				#	"Progressive Rock", "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour",
				#	"Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove", "Satire", "Slow Jam", "Club",
				#	"Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhytmic Soul", "Freestyle", "Duet", "Punk Rock", "Drum Solo", "Acapella",
				#	"Euro-House", "Dance Hall", "Goa", "Drum & Bass", "Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", "Polsk Punk",
				#	"Beat", "Christian Gangsta", "Heavy Metal", "Black Metal", "Crossover", "Contemporary C", "Christian Rock", "Merengue", "Salsa",
				#	"Thrash Metal", "Anime", "JPop", "SynthPop" };

				#$id3v2 = new ID3v2($mp3_file_name);
				#$id3v2->tyer->text = $str;
				#$id3v2->write();

			}
		break;
		case 'track':
			if ($header_version < 0)
			{
				$id3v1 = new ID3v1();
				$id3v1->setTrack($str);
				$id3v1->write($mp3_file_name);
			}
			else
			{
				$id3v2 = new ID3v2($mp3_file_name);
				$id3v2->trck->text = $str;
				$id3v2->write();

			}
		break;
	}
}
#TEST /17.05.2009/
function playlist_to_m3u($uname_id)#TEST /17.05.2009/
{
	include ("../config.php");

	$url = $DOC_ROOT.$MUSIC_DIR.$uname_id."/";
	$m3u = "#EXTM3U\n";

	if (is_dir($url))
	{

		if ($dir = opendir($url))
		{
			$c=1;
			while (false !== ($file = readdir($dir)))
			{

				if ($file != "." && $file != "..")
				{
					$tag = mp3_tags_read($url.$file);
					$title=$tag['title'];

					if ($title == NULL) $title = $file;

					#TODO: способ узнавать длинну(время) воспроизведения файла
					#$m3u = $m3u. "#EXTINF:".$length.",".$title."\nhttp://xepec.ru/".$MUSIC_DIR.$uname_id."/".$file.".\n";
					$m3u = $m3u."#EXTINF,".$title."\nhttp://xepec.ru/".$MUSIC_DIR.$uname_id."/".$file.".\n";
				$c++;
				}
			}
		}
		closedir($dir);
	}
	return $m3u;
}

#TEST /17.05.2009/
function playlist_to_pls($uname_id)#TEST /17.05.2009/
{
	include ("../config.php");

	$url = $DOC_ROOT.$MUSIC_DIR.$uname_id."/";
	$pls="[playlist]\n\n";

	if (is_dir($url))
	{

		if ($dir = opendir($url))
		{
			$c=1;
			while (false !== ($file = readdir($dir)))
			{

				if ($file != "." && $file != "..")
				{
					$tag = mp3_tags_read($url.$file);
					$title=$tag['title'];

					if ($title == NULL) $title = $file;

					$pls = $pls."File".$c."= http://xepec.ru/".$MUSIC_DIR.$uname_id."/".$file.".\n\n";
					$pls = $pls."Title".$c."=".$title."\n\n";

					#TODO: способ узнавать длинну(время) воспроизведения файла
					$pls = $pls."Length".$c."=".$length."\n\n";
				$c++;
				}
			}
		}
		closedir($dir);
	}
	return $pls;
}
?>
